package com.ukao.cashregister.ui.stokin;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.AddClothingAdapter;
import com.ukao.cashregister.base.BaseFragment;
import com.ukao.cashregister.bean.AddClothingItem;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.eventbus.AppEvent;
import com.ukao.cashregister.eventbus.ChildFragmentEvent;
import com.ukao.cashregister.eventbus.PayAmountEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.widget.ClearEditText;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.seach_layout;

/**
 * Created by ukaodev on 2017/5/24.
 */

@SuppressLint("ValidFragment")
public class ChooseClothingProjectChildFragment extends BaseFragment {


    @BindView(R.id.key_search_btn)
    Button keySearchBtn;

    @BindView(R.id.key_add_btn)
    Button keyAddBtn;
    @BindView(R.id.remove_recycler)
    RecyclerView removeRecycler;
    @BindView(R.id.add_edit)
    ClearEditText addEdit;
    @BindView(R.id.add_btn)
    Button addBtn;
    @BindView(R.id.add_layout)
    RelativeLayout addLayout;
    @BindView(R.id.all_recycler)
    RecyclerView allRecycler;
    @BindView(R.id.seach_recycler)
    RecyclerView seachRecycler;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(seach_layout)
    FrameLayout seachLayout;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_btn)
    Button searchBtn;

    @BindView(R.id.keyboard_layout)
    LinearLayout keyboardLayout;


    //是否为单选模式
    private boolean isSingle;


    private AddClothingItem data;
    private AddClothingAdapter mAdapter;

    ;
    private String id = "";
    private String mercBusinessId = "";
    private String currentParentId;
    private String pricingMode;
    private String orderId;
    private StringBuffer mSearchBuffer;
    private ArrayList<AddClothingItem> mSearchlist;


    private List<AddClothingItem> mAddClothingItem;
    private Unbinder unbinder;
    private boolean mHasLoadedOnce;

    /**
     * @return
     */
    public static ChooseClothingProjectChildFragment getInstance(String id, String mercBusinessId, String currentParentId, String pricingMode, String orderId) {
        ChooseClothingProjectChildFragment childFragment = new ChooseClothingProjectChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, id);
        bundle.putString(ARG_PARAM2, mercBusinessId);
        bundle.putString(ARG_PARAM3, currentParentId);
        bundle.putString(ARG_PARAM4, pricingMode);
        bundle.putString(ARG_PARAM5, orderId);
        childFragment.setArguments(bundle);
        return childFragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString(ARG_PARAM1);
            mercBusinessId = getArguments().getString(ARG_PARAM2);
            currentParentId = getArguments().getString(ARG_PARAM3);
            pricingMode = getArguments().getString(ARG_PARAM4);
            orderId = getArguments().getString(ARG_PARAM5);
        }

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_addclothing_project, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();

    }


    private void getclothingData() {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        L.i("pricingMode=" + pricingMode);
        mHashMap.put("orderId", orderId);
        mHashMap.put("typeId", id);
        mHashMap.put("pricingMode", pricingMode);
        mHashMap.put("mercBusinessId", mercBusinessId);
        mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
        addSubscription(apiStores().productInfo(Constant.createParameter(mHashMap)),
                new ApiCallback<AddClothingItem>() {


                    @Override
                    public void onSuccess(AddClothingItem model) {
                        dismissProgressDialog();
                        if (model.getHttpCode() == 200) {
                            mHasLoadedOnce = true;
                            mAddClothingItem = model.getData();
                            mAdapter.setDatas(model.getData());
                            fillData();
                        } else {

                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });
    }


    private void fillData() {
        if (!CheckUtils.isEmpty(currentParentId)) {

            for (int i = 0; i < mAddClothingItem.size(); i++) {
                if (mAddClothingItem.get(i).getId().equals(currentParentId)) {
                    data = mAddClothingItem.get(i);
                    mAddClothingItem.get(i).setCheck(true);
                }
                ;

            }
            mAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void initView() {
        seachLayout.setVisibility(View.VISIBLE);
        allRecycler.setVisibility(View.GONE);
        mSearchlist = new ArrayList<>();
        keyAddBtn.setVisibility(View.GONE);
        mSearchBuffer = new StringBuffer();
         List<AddClothingItem> mAllData = new ArrayList<>();
        mAdapter = new AddClothingAdapter(activity, mAllData, R.layout.activity_addclothing_list_item);
        mAdapter.setOnItemClickListener(mOnItemClickListener);
        initGridRecyclerView(seachRecycler, 2);
        seachRecycler.setAdapter(mAdapter);


    }

    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {

        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int pos) {
            super.onItemClick(viewGroup, view, o, pos);
            if (CheckUtils.isEmpty(  mAdapter.getDatas()))return;
            if (mAdapter.getItem(pos) != null) {
                updateItem(mAdapter.getItem(pos), pos);
            }


        }


    };

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!mHasLoadedOnce){
            getclothingData();
        }

    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();

        if (mHasLoadedOnce && mAddClothingItem != null&& mAddClothingItem.size()!=0 && mAddClothingItem.size() != mAdapter.getDatas().size() ) {
            mAdapter.setDatas(mAddClothingItem);
            mAdapter.notifyDataSetChanged();
        }
        searchEdit.setText("");
        noData.setVisibility(View.GONE);
        if (mSearchBuffer != null)
            mSearchBuffer.setLength(0);
    }


    public void updateItem(AddClothingItem o, int pos) {
        data = o;
        if (data.isCheck()) return;
        data.setCheck(true);
        for (int i = 0; i < mAddClothingItem.size(); i++) {
            if (mAddClothingItem.get(i) != data) {
                mAddClothingItem.get(i).setCheck(false);
            }
        }

        ChildFragmentEvent.<AddClothingItem>postHasData(ChildFragmentEvent.Message.checked, data);
        Map map = new HashMap();
        map.put("position", pos);
        map.put("parentId", data.getId());
        map.put("name", data.getName());
        map.put("unitText", data.getUnitText());
        map.put("isCustomNum", data.getIsCustomNum());
        map.put("proTypeId", id);
        map.put("saleType", data.getSaleType());
        map.put("discount", data.getDiscount());
        AppEvent.postHasData(AppEvent.Message.update, map);
        AppEvent.postNoData(AppEvent.Message.next);
        mAdapter.notifyDataSetChanged();
        searchEdit.setText("");
        map.clear();
        map = null;
        mAdapter.getDatas().clear();
        mAdapter.notifyDataSetChanged();

    }

    public List<AddClothingItem> getLoadData() {
        return mAdapter.getDatas();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacksAndMessages(null);
        unbinder.unbind();
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }






    @Subscribe
    public void onEvent(ChildFragmentEvent event) {

        if (event.getMessage().equals(ChildFragmentEvent.Message.checked)) {
            String parentId = ((AddClothingItem) event.getData()).getId();
            if (data == null && mAddClothingItem == null) return;
            if (!data.getId().equals(parentId)) {
                for (int i = 0; i < mAddClothingItem.size(); i++) {
                    mAddClothingItem.get(i).setCheck(false);
                }
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    public void setSeektoPosition(int position) {
        // mSearchRecycler.scrollToPosition(position);
    }

    Handler mHandler = new Handler();

    @OnClick({R.id.add_btn, R.id.search_btn, R.id.key_search_btn, R.id.key_add_btn,
            R.id.Button1, R.id.Button2, R.id.Button3, R.id.Button4, R.id.Button5, R.id.Button6, R.id.Button7, R.id.Button8, R.id.Button9, R.id.Button10, R.id.Button11, R.id.Button12, R.id.Button13, R.id.Button14, R.id.Button15, R.id.Button16, R.id.Button17, R.id.Button18, R.id.Button19, R.id.Button20, R.id.Button21, R.id.Button22, R.id.Button23, R.id.Button24, R.id.Button25, R.id.Button26, R.id.Button27})
    public void onViewClicked(View view) {
        onButtonClick(view);
    }

    public void onButtonClick(View view) {
        if (view.getId() == R.id.Button27) {
            if ( !CheckUtils.isEmpty(mAddClothingItem)) {
                mAdapter.setDatas(mAddClothingItem);
                mAdapter.notifyDataSetChanged();
                noData.setVisibility(View.GONE);

            }

            mSearchBuffer.setLength(0);
            searchEdit.setText("");

        } else {

            if (!mHasLoadedOnce) {
                T.show(getString(R.string.no_data_was_obtained));
                return;
            }
            if (CheckUtils.isEmpty(mAddClothingItem)){
                T.show(getString(R.string.current_list_numerous));
                return;
            }

            Button mButton = (Button) view;
            mSearchBuffer.append(mButton.getText().toString().trim());
            searchEdit.setText(mSearchBuffer.toString());
            mHandler.removeCallbacksAndMessages(null);
            mHandler.postDelayed(() -> {
                String searchContext = getText(searchEdit);
                if (searchContext.isEmpty()) return;
                try {
                    mSearchlist.clear();
                    for (int i = 0; i < mAddClothingItem.size(); i++) {
                        AddClothingItem mitem = mAddClothingItem.get(i);
                        if (mitem.getName().contains(searchContext)) {
                            mSearchlist.add(mitem);
                        } else if (mitem.getFirstWord().toLowerCase().contains(searchContext.toLowerCase())) {
                            mSearchlist.add(mitem);
                        }
                    }
                    noData.setVisibility(mSearchlist.size() == 0 ? View.VISIBLE : View.GONE);
                    mAdapter.setDatas(mSearchlist);
                } catch (Exception e) {

                }
            }, 1000);
        }
    }
}
